<?php

namespace Tag;

use W3\Util;
use Base\Metas;

/**
 * 标签云组件
 *
 * @author edikud
 * @date 2022/10/22
 * @copyright Copyright (c) 2022 W3 (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Rows extends Metas
{
    /**
     * 初始化
     *
     * @access protected
     * @return void
     */
    protected function init()
    {
		# 定义变量默认数据
        $this->parameter([
			
		    'field' => '*',		
			'ignoreZeroCount' => false,
		    'sort' => 'count',
            'desc' => true,
			'offset' => 0,
			'limit' => 0
			
		], true);
	}
	
    /**
     * 入口函数
     *
     * @access public
     * @return void
     */
    public function execute()
    {
		$pass = false;
        $select = $this->db
		    ->select()
			->from('table.metas')
		    ->where('type = ?', 'tag');
			
		if($this->parameter->alias){ 
		    $select->where('alias = ?', $this->parameter->alias);
			$pass = true;
		}
			
		if($this->parameter->mid){
			if(FALSE !== strpos($this->parameter->mid, ',')){ 
	            $midList = array_filter(explode(',', $this->parameter->mid), function($val){
	                return is_numeric($val);
	            });
				if($midList){ 
				    $select->where('mid IN ('.substr( str_repeat( '?,', count( $midList ) ), 0, - 1 ).')', $midList);
				    $pass = true;
				} else {
				    $pass = false;
			    }
			}else{
		        $select->where('mid = ?', $this->parameter->mid);
				$pass = true;
			}
		}
			
		if($this->parameter->sort){
			$select->order('table.metas.' . $this->parameter->sort, $this->parameter->desc ? 'DESC' : 'ASC');
		} 

        /** 忽略零数量 */
        if ($this->parameter->ignoreZeroCount) {
            $select->where('count > 0');
        }

        /** 总数限制 */
        if ($this->parameter->limit) {
            $select->limit($this->parameter->limit);
        }

        if($pass){
			if(isset($midList)){
			    $list = Util::arrayChangeKey($select->get(), 'mid');
                foreach ($midList as $v) {
                    isset($list[$v]) && $this->push($list[$v]);
                }
			} else {
			    if($this->parameter->sort){
				    $select->order('table.metas.' . $this->parameter->sort, $this->parameter->desc ? 'DESC' : 'ASC');
			    } 
				$select->get([$this, 'push']);
			}
        }
    }

    /**
     * 按分割数输出字符串
     *
     * @param ...$args 需要输出的值
     */
    public function cloud(...$args)
    {
        array_unshift($args, $this->count);
        echo call_user_func_array([Util::class, 'splitCount'], $args);
    }
}
